package com.yixun.qfbao.utils;

import com.yixun.qfbao.api.service.TokenService;
import com.yixun.qfbao.model.Token;
import com.yixun.qfbao.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtils {
    private static final Logger log = LoggerFactory.getLogger(LoginUtils.class);

    @Autowired
    private TokenService tokenService;

    public void putToken(Token token) {
        try {
            RedisUtil.set(token.getStrToken(), token);
        } catch (Exception e) {
            log.info("token缓存失败:" + e.getMessage());
        }
    }

    public void putCache(Object key, Object object) {
        try {
            RedisUtil.set(String.valueOf(key), object);
        } catch (Exception e) {
            log.info("token缓存失败:" + e.getMessage());
        }
    }

    public void removeToken(Object key) {
        try {
            RedisUtil.delete(String.valueOf(key));
        } catch (Exception e) {
            log.info("token缓存失败:" + e.getMessage());
        }
    }

    public Token getToken(Object key) {
        Token token = null;
        try {
            //采用Redis缓存
            token = RedisUtil.get(String.valueOf(key), Token.class);
        } catch (Exception e) {
            log.info("获取token缓存失败:" + e.getMessage());
            return null;
        }
        return token;

    }

    public void put(String key, Object object) {
        try {
            //采用Redis缓存
            RedisUtil.set(key, object);

        } catch (Exception e) {
            log.info("token缓存失败:" + e.getMessage());
        }
    }

    public Object get(Object key){
        try {
            return RedisUtil.get(String.valueOf(key));
        } catch (Exception e) {
            log.error("查询缓存失败,KEY= {}" + key);
        }
        return null;
    }

    /**
     * 检查token
     * @param strToken
     * @return
     */
    public boolean checkToken(String strToken,String companyUuid){
        try{
            Token t = getToken(strToken);
            if(t == null){
                t = tokenService.getLastToken(companyUuid);
                if(t == null){
                    return false;
                }
            }
            if(t.getValidTime().after(new Date())){
                return true;
            }else{
                return false;
            }

        }catch (Exception e){
            log.error("checkToken companyUuid: {}, strToken: {}, error: ", companyUuid, strToken, e);
            return false;
        }
    }
}
